package com.fowo.api.sys.performance;

import com.fowo.api.common.util.ListUtils;
import com.fowo.api.sys.performance.model.PerformanceLogModel;
import com.fowo.api.sys.performance.properties.PerformanceLogProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * 性能日志服务
 * @author yl_ls
 */
@Slf4j
@Service
public class PerformanceLogService {
    @Resource
    private Collection<PerformanceLogWriter> performanceLogWriters;

    @Resource
    private PerformanceLogProperties properties;

    private PerformanceLogWriter currentWriter;

    public void write(PerformanceLogModel logModel) {
        if (currentWriter == null || !properties.getWriter().isAssignableFrom(currentWriter.getClass())) {
            currentWriter = ListUtils.find(performanceLogWriters, w -> properties.getWriter().isAssignableFrom(w.getClass()));
        }
        if (currentWriter != null) {
            try {
                currentWriter.write(logModel);
            } catch (Exception e) {
                log.error("未能写入性能日志", e);
            }
        }
    }
}
